package controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import pojo.Majors;
import pojo.Status;
import pojo.Tokens;
import service.MajorService;
import service.TokenService;
import service.impl.MajorServiceImpl;
import service.impl.TokenServiceImpl;
import utils.JSONUtils;
import utils.TokenUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RequestMapping("/api/major")
@RestController
public class MajorController {

    private MajorService majorService = new MajorServiceImpl();
    private TokenService tokenService = new TokenServiceImpl();


    @GetMapping
    public void sdeptMajor(HttpServletRequest request, HttpServletResponse response) throws IOException {


        String accessToken = request.getHeader("AccessToken");
        Tokens tokens = tokenService.queryByToken(accessToken);
        JSONObject jsonObject = new JSONObject();
        if (TokenUtils.decrypt(tokens)) {

            String sdeptId = request.getParameter("sdeptId");

            List<Majors> majorsList = majorService.queryAllMajorBySdeptId(sdeptId);

            jsonObject.put(Status.CODE, Status.OK);
            jsonObject.put(Status.MSG, "系id为" + sdeptId + "下的所有专业查询成功");
            jsonObject.put("data", majorsList);

        } else {
            jsonObject.put(Status.CODE, Status.UNAUTHORIZED);
            jsonObject.put(Status.MSG, "请登录");

        }

        JSONUtils.responseJson(response, jsonObject.toJSONString());
    }

    @PostMapping("/create")
    public void create(@RequestBody Majors major, HttpServletRequest request, HttpServletResponse response) throws IOException {

        String accessToken = request.getHeader("AccessToken");
        Tokens tokens = tokenService.queryByToken(accessToken);
        JSONObject jsonObject = new JSONObject();
        if (TokenUtils.decrypt(tokens)) {
            int i = majorService.registStudent(major);

            if (i == -1) {
                jsonObject.put(Status.CODE, Status.BAD_REQUEST);
                jsonObject.put(Status.MSG, major.getName() + "专业添加失败");
            } else {
                jsonObject.put(Status.CODE, Status.OK);
                jsonObject.put(Status.MSG, major.getName() + "专业添加成功");
            }

        } else {
            jsonObject.put(Status.CODE, Status.UNAUTHORIZED);
            jsonObject.put(Status.MSG, "请登录");

        }

        JSONUtils.responseJson(response, jsonObject.toJSONString());
    }


}
